package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.constant.UserConstants;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.SpringUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.TranslationUtil;
import com.ruoyi.common.core.utils.bean.BeanUtils;
import com.ruoyi.common.datascope.service.AwaitUserService;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.params.SysRoleParams;
import com.ruoyi.system.exception.SystemException;
import com.ruoyi.system.mapper.SysRoleDeptMapper;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.mapper.SysRoleMenuMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 角色 业务层处理
 *
 * @author ruoyi
 */
@Service
@Slf4j
public class SysRoleServiceImpl implements ISysRoleService {
    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysUserMapper userMapper;


    @Autowired
    private SysRoleMenuMapper roleMenuMapper;

    @Autowired
    private ISysRoleMenuService sysRoleMenuService;

    @Autowired
    private ISysRoleDeptService sysRoleDeptService;

    @Autowired
    private SysRoleDeptMapper roleDeptMapper;

    @Autowired
    private AwaitUserService awaitUserService;

    @Autowired
    private ISysDeptService sysDeptService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysLanguageDataService sysLanguageDataService;

    /**
     * 根据条件分页查询角色数据
     *
     * @param role 角色信息
     * @return 角色数据集合信息
     */
    @Override
//    @DataScope(deptAlias = "d")
    public Page<SysRole> selectRoleList(Page<SysRole> page, SysRoleParams role) {
        Long deptId = role.getDeptId();
        List<Long> deptIds = sysDeptService.selectDeptAncestors(deptId);
        deptIds.add(deptId);
        role.setDeptIds(deptIds);
        role.setDeptId(null);
        Page<SysRole> listPage = roleMapper.selectRoleList(page,role);
        List<SysRole> sysRoleOldList = listPage.getRecords();
        List<SysRole> sysRoleList = new ArrayList<>();
        Map<String, SysRole> sysRoleOldMap = new HashMap<>();
        for (SysRole sysRole : sysRoleOldList) {
            //需要添加删除状态作为唯一标识 否则可能会拿到删除的数据  后设计数据只有一条 如果存在删除的就激活
            sysRoleOldMap.put(sysRole.getDeptId() + "_" + sysRole.getRoleKey(), sysRole);
        }
        Map<String, SysRole> sysRoleNewMap = new HashMap<>();
        for (SysRole sysRole : sysRoleOldList) {
            if (sysRoleNewMap.get(sysRole.getRoleKey()) == null) {
                SysRole sysRoleNew = null;
                SysRole sysRoleTopFloor = null;
                for (Long deptIdTemp : deptIds) {
                    SysRole sysRoleTemp = sysRoleOldMap.get(deptIdTemp + "_" + sysRole.getRoleKey());
                    //当存在的时候
                    if (sysRoleTemp != null) {
                        //当删除的时候 不显示
                     /*   if(sysRoleTemp.getDelFlag().equals("2") && deptIdTemp.equals(deptId)){
//                            sysRoleNew = null;
                        }else */
        /*                if(sysRoleTemp.getDelFlag().equals("0") &&
                            (sysRoleTemp.getIsAllowExtends().equals("Y") || deptIdTemp.equals(deptId))) {

                            if (sysRoleTopFloor == null) {
                                sysRoleTopFloor = sysRoleTemp;
                            }
                        }*/

                        if (sysRoleTemp.getIsAllowExtends().equals("Y") || deptIdTemp.equals(deptId)) {
                            if (sysRoleTemp.getDelFlag().equals("0")) {
                                if (sysRoleTopFloor == null) {
                                    sysRoleTopFloor = sysRoleTemp;
                                }
                            }
                            if (sysRoleNew == null) {
                                sysRoleNew = new SysRole();
                            }
                            //当为删除了的时候只继承删除 其他不继承
                            if (sysRoleTemp.getDelFlag().equals("2")) {
                                sysRoleNew.setDelFlag("2");
                            } else {
                                BeanUtils.copyPropertiesIgnoreNull(sysRoleTemp, sysRoleNew);
                            }

                        }
                    }
                }

                //过滤掉删除的
                if (sysRoleNew != null && !sysRoleNew.getDelFlag().equals("2")) {
                    //当顶层的部门号与当前部门号相同的时候证明是顶层
                    if (sysRoleTopFloor.getDeptId().equals(deptId)) {
                        sysRoleNew.setIsTopFloor("Y");
                    } else {
                        sysRoleNew.setIsTopFloor("N");
                    }
                    sysRoleList.add(sysRoleNew);
                    sysRoleNewMap.put(sysRoleNew.getRoleKey(), sysRoleNew);
                }
            }
        }

        Collections.sort(sysRoleList, new Comparator<SysRole>() {
            @Override
            public int compare(SysRole o1, SysRole o2) {
                Integer sort1 = o1.getRoleSort() == null ? 0 : o1.getRoleSort();
                Integer sort2 = o2.getRoleSort() == null ? 0 : o2.getRoleSort();
                return sort1 > sort2 ? 1 : sort1.equals(sort2) ? 0 : -1;
            }
        });
        sysRoleList.forEach(r -> {
            SysLanguageData languageData = sysLanguageDataService.selectByRef(r.getRoleId(), "role");
            if (languageData != null) {
                TranslationUtil.translation(languageData.getValue(),r);
            }
        });
        listPage.setRecords(sysRoleList);
        return listPage;
    }


    /**
     * 根据用户ID查询权限
     *
     * @param userId 用户ID
     * @return 权限列表
     */
    @Override
    public Set<String> selectRolePermissionByUserId(Long userId) {
    /*    List<SysRoleDto> perms = roleMapper.selectRolePermissionByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (SysRoleDto perm : perms) {
            if (StringUtils.isNotNull(perm)) {
                permsSet.addAll(Arrays.asList(perm.getRoleKey().trim().split(",")));
            }
        }
        return permsSet;*/
        List<SysRole> selectRoleList = this.selectRoleListByUserId(userId);

        Set<String> permsSet = new HashSet<>();
        for (SysRole perm : selectRoleList) {
            if (StringUtils.isNotNull(perm)) {
                permsSet.addAll(Arrays.asList(perm.getRoleKey().trim().split(",")));
            }
        }
        return permsSet;
    }

    /**
     * 查询所有角色
     *
     * @return 角色列表
     */
    @Override
    public List<SysRole> selectRoleAll() {
        Page<SysRole> page = new Page<>(1, -1);
        return SpringUtils.getAopProxy(this).selectRoleList(page,new SysRoleParams()).getRecords();
    }

    /**
     * 根据用户ID获取角色选择框列表
     *
     * @param userId 用户ID
     * @return 选中角色ID列表
     */
    @Override
    public List<SysRole> selectRoleListByUserId(Long userId) {
        SysUser sysUser = userMapper.selectUserById(userId);
        return selectRoleListByUser(sysUser);
    }

    @Override
    public List<SysRole> selectRoleListByUser(SysUser sysUser) {
        SysRoleParams sysRoleParams = new SysRoleParams();
        sysRoleParams.setDeptId(sysUser.getDeptId());
        sysRoleParams.setUserId(sysUser.getUserId());
        Page<SysRole> page = new Page<>(1, -1);
        List<SysRole> sysRoleList = this.selectRoleList(page,sysRoleParams).getRecords();

        for (SysRole sysRole : sysRoleList) {
            Set<Long> deptSet = new HashSet<>();
            Map<String, Set<Long>> dataScopes = sysRole.getDataScopes();
            dataScopes = dataScopes == null ? new HashMap<>() : dataScopes;
            //自定义数据权限
            if (sysRole.getDataScope().equals("2")) {
                deptSet.addAll(sysRoleDeptService.getRoleDeptContainSelf(sysUser.getDeptId(), sysRole.getRoleKey()));
                dataScopes.put("type2", deptSet);
                sysRole.setDataScopes(dataScopes);
            } else if (sysRole.getDataScope().equals("4")) {
                deptSet.addAll(sysDeptService.getDeptIdAndBelowByDeptId(sysUser.getDeptId()));
                dataScopes.put("type4", deptSet);
                sysRole.setDataScopes(dataScopes);
            }
        }

        return sysRoleList;
    }

    /**
     * 通过角色ID查询角色
     *
     * @param roleId 角色ID
     * @return 角色对象信息
     */
/*    public SysRoleDto selectRoleById(Long roleId) {
        SysRoleDto sysRole = roleMapper.selectRoleById(roleId);
        SysRoleDto sysRoleNew = selectRole(sysRole.getDeptId(),sysRole.getRoleKey());
        sysRole = sysRoleNew!=null?sysRoleNew:sysRole;
        return sysRole;
    }*/

    /**
     * 根据deptId和roleKey  原始数据
     *
     * @return
     */
    @Override
    public SysRole selectRole(Long deptId, String roleKey) {
        SysRole sysRole = null;
        SysRoleParams sysRoleParams = new SysRoleParams();
        sysRoleParams.setRoleKey(roleKey);
        sysRoleParams.setDeptId(deptId);
        Page<SysRole> page = new Page<>(1, -1);
        List<SysRole> selectRoleList = this.selectRoleList(page,sysRoleParams).getRecords();
        if (selectRoleList.size() > 0) {
            sysRole = selectRoleList.get(0);
            Set<Long> sysRoleMenuSet = sysRoleMenuService.getRoleMenuContainSelf(deptId, roleKey, null);
            sysRole.setMenuIds(sysRoleMenuSet.toArray(new Long[sysRoleMenuSet.size()]));
        }

        return sysRole;
    }


    /**
     * 校验角色名称是否唯一
     *
     * @return 结果
     */
    @Override
    public String checkRoleNameUnique(Long roleId, Long deptId, String roleName) {
        roleId = StringUtils.isNull(roleId) ? -1L : roleId;
        SysRole info = roleMapper.checkRoleNameUnique(deptId, roleName);
        if (StringUtils.isNotNull(info) && info.getRoleId().longValue() != roleId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验角色权限是否唯一
     *
     * @return 结果
     */
    @Override
    public String checkRoleKeyUnique(Long roleId, Long deptId, String roleKey) {
        roleId = StringUtils.isNull(roleId) ? -1L : roleId;
        SysRole info = roleMapper.checkRoleKeyUnique(deptId, roleKey);
        if (StringUtils.isNotNull(info) && info.getRoleId().longValue() != roleId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验角色是否允许操作
     *
     * @param role 角色信息
     */
    @Override
    public void checkRoleAllowed(SysRole role) {
        if (StringUtils.isNotNull(role.getRoleId()) && role.isAdmin()) {
//            throw new CustomException("不允许操作超级管理员角色");
        }
    }

    /**
     * 通过角色ID查询角色使用数量
     *
     * @return 结果
     */
//    @Override
/*    public int countUserRole(Long deptId,String roleKey) {
//        return userRoleMapper.countUserRoleByRoleId(roleId);
        return  0;
    }*/

    /**
     * 新增保存角色信息
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertRole(SysRole role) {
        if (UserConstants.NOT_UNIQUE.equals(this.checkRoleNameUnique(role.getRoleId(), role.getDeptId(), role.getRoleName()))) {
            throw new SystemException(SystemException.NOT_ALLOW_INSERT).setBusinessMessage("新增角色'" + role.getRoleName() + "'失败，角色名称已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(this.checkRoleKeyUnique(role.getRoleId(), role.getDeptId(), role.getRoleKey()))) {
            throw new SystemException(SystemException.NOT_ALLOW_INSERT).setBusinessMessage("新增角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }

        int successNum = 0;
        //当存在的时候
        SysRole sysRoleOrigin = roleMapper.selectRoleByDeptAndKey(role.getDeptId(), role.getRoleKey());
        if (sysRoleOrigin != null && "2".equals(sysRoleOrigin.getDelFlag())) {
            SysRole roleUpdate = new SysRole();
            roleUpdate.setRoleId(sysRoleOrigin.getRoleId());
            roleUpdate.setDelFlag("0");
            roleMapper.updateRole(roleUpdate);
            successNum = this.updateRole(role);
        } else {
            role.setDataScope("4");
            // 新增角色信息
            successNum = roleMapper.insertRole(role);
            List<SysRoleMenu> sysRoleMenus = sysRoleMenuService.getDiffRoleMenu(role.getDeptId(), role.getRoleKey(), role.getMenuIds(), null);
            if (sysRoleMenus.size() > 0) {
                for (SysRoleMenu sysRoleMenu : sysRoleMenus) {
                    sysRoleMenu.setRoleId(role.getRoleId());
                }
                successNum = roleMenuMapper.batchRoleMenu(sysRoleMenus);
            }
        }

        return successNum;
    }

    //检查是否有继承  获取继承  前提条件是允许继承
    public List<SysRole> getExtendRoles(Long deptId, String roleKey) {
        SysRoleParams sysRoleParams = new SysRoleParams();
        sysRoleParams.setRoleKey(roleKey);
        sysRoleParams.setDeptId(deptId);
        sysRoleParams.setStatus("");
        Page<SysRole> page = new Page<>(1, -1);
        List<SysRole> sysRoleList = roleMapper.selectRoleList(page,sysRoleParams).getRecords();
        for (int i = 0; i < sysRoleList.size(); i++) {
            SysRole sysRole = sysRoleList.get(i);
            if (sysRole.getDeptId().equals(deptId)) {
                sysRoleList.remove(i);
                i--;
            }
        }
        return sysRoleList;
    }

    /**
     * 修改保存角色信息
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateRole(SysRole role) {

        if (role.getRoleId() == null) {
            SysRole SysRoleTemp = selectRole(role.getDeptId(), role.getRoleKey());
            role.setRoleId(SysRoleTemp.getRoleId());
        }

        SysRole sysRoleOrigin = roleMapper.selectRoleById(role.getRoleId());
        SysRole roleOld = this.selectRole(sysRoleOrigin.getDeptId(), sysRoleOrigin.getRoleKey());


        //判断是否为顶层
        if (!roleOld.getIsTopFloor().equals("Y")) {
            if (role.getRoleKey() != null && !role.getRoleKey().equals(roleOld.getRoleKey())) {
                throw new SystemException(SystemException.NOT_ALLOW_UPDATE).setBusinessMessage("不是原始角色不允许修改权限标识");
            }

            //不是原始的角色 不允许修改是否继承
            if (role.getIsAllowExtends() != null && !roleOld.getIsAllowExtends().equals(role.getIsAllowExtends())) {
                throw new SystemException(SystemException.NOT_ALLOW_UPDATE).setBusinessMessage("不是原始角色不允许修改继承标识");
            }
        }

        if (role.getIsAllowExtends() != null) {
            if (roleOld != null && roleOld.getIsAllowExtends() != null && roleOld.getIsAllowExtends().equals(role.getIsAllowExtends())) {
                role.setIsAllowExtends(null);
            } else if (role.getIsAllowExtends().equals("N")) {//当改为不允许继承的时候需要判断是否已经继承了
                if (getExtendRoles(roleOld.getDeptId(), roleOld.getRoleKey()).size() > 0) {
                    if (role.getIsAllowExtends() != null && !roleOld.getIsAllowExtends().equals(role.getIsAllowExtends())) {
                        throw new SystemException(SystemException.NOT_ALLOW_UPDATE).setBusinessMessage("该角色存在继承，不允许修改继承标识");
                    }
                }
            }
        }

        if (UserConstants.NOT_UNIQUE.equals(this.checkRoleNameUnique(role.getRoleId(), role.getDeptId(), role.getRoleName()))) {
            throw new SystemException(SystemException.NOT_ALLOW_UPDATE).setBusinessMessage("修改角色'" + role.getRoleName() + "'失败，角色名称已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(this.checkRoleKeyUnique(role.getRoleId(), role.getDeptId(), role.getRoleKey()))) {
            throw new SystemException(SystemException.NOT_ALLOW_UPDATE).setBusinessMessage("修改角色'" + role.getRoleName() + "'失败，角色已存在");
        }

        //当已经删除
        if (sysRoleOrigin != null) {
            if (sysRoleOrigin.getDelFlag().equals("2")) {
                BeanUtils.copyPropertiesIgnoreNull(sysRoleOrigin, roleOld);
                role.setDelFlag("0");//启用
            }
        }


        //如果是顶层修改权限标识 要校验底层是否已经引用过
        if (!roleOld.getRoleKey().equals(role.getRoleKey())) {
            //批量修改子的  这里存在一个问题如果子部门存在需要修改的部门的话会出现重复的 先人为控制 待以后再优化
            this.batchUpdateRoleKey(roleOld.getDeptId(), roleOld.getRoleKey(), role.getRoleKey());
            //还需要修改sys_role_dept sys_role_menu
        }

        //当新的和老的没有变化的时候不需要替换

        if (roleOld.getRoleName() != null && roleOld.getRoleName().equals(role.getRoleName())) {
            role.setRoleName(null);
        }

        if (roleOld.getRoleSort() != null && roleOld.getRoleSort().equals(role.getRoleSort())) {
            role.setRoleSort(null);
        }

        if (roleOld.getDataScope() != null && roleOld.getDataScope().equals(role.getDataScope())) {
            role.setDataScope(null);
        }

        if (roleOld.getStatus() != null && roleOld.getStatus().equals(role.getStatus())) {
            role.setStatus(null);
        }

        if (roleOld.getRemark() != null && roleOld.getRemark().equals(role.getRemark())) {
            role.setRemark(null);
        }

        if (roleOld.getDelFlag() != null && roleOld.getDelFlag().equals(role.getDelFlag())) {
            role.setDelFlag(null);
        }

        if (roleOld.getIsAllowExtends() != null && roleOld.getIsAllowExtends().equals(role.getIsAllowExtends())) {
            role.setIsAllowExtends(null);
        }


        List<SysRoleMenu> sysRoleMenus = null;
        if (role.getMenuIds() != null) {
            sysRoleMenus = sysRoleMenuService.getDiffRoleMenu(role.getDeptId(), role.getRoleKey(), role.getMenuIds(), null);
        }

        List<SysRoleDept> sysRoleDepts = null;
        if (role.getDeptIds() != null) {
            sysRoleDepts = sysRoleDeptService.getDiffRoleDept(role.getDeptId(), role.getRoleKey(), role.getDeptIds());
        }

/*        List<SysRoleDept> sysRoleDepts = null;
        if(role.getDeptIds()!=null){
            sysRoleDepts=this.getDiffRoleDept(role.getDeptId(),role.getRoleKey(),role.getMenuIds());
        }*/


        boolean isEditData = false;//是否有修改数据
        if (role.getRoleName() != null || role.getRoleSort() != null
                || role.getDataScope() != null || role.getStatus() != null
                || role.getDelFlag() != null || role.getIsAllowExtends() != null
                || role.getRemark() != null || (sysRoleMenus != null && sysRoleMenus.size() > 0)
                || (sysRoleDepts != null && sysRoleDepts.size() > 0)) {
            isEditData = true;
        }
        role.setUpdateTime(DateUtils.getNowDate());
        role.setUpdateBy(SecurityUtils.getUsername());
        int successNum = 0;
        if (!roleOld.getDeptId().equals(role.getDeptId()) && isEditData) {
            role.setRoleId(null);
            if (role.getIsAllowExtends() == null) {
                role.setIsAllowExtends("Y");
            }
            successNum = roleMapper.insertRole(role);
//            throw new SystemException(SystemException.NOT_ALLOW_UPDATE).setBusinessMessage("不允许修改部门");
            //当部门不同的时候证明这个部门没有 需要添加
        } else {
            // 修改角色信息
            successNum = roleMapper.updateRole(role);
        }

        if (role.getRoleId() != null && sysRoleMenus != null) {
            roleMenuMapper.deleteRoleMenuByRoleId(role.getRoleId(), role.getProjectCodes());
        }

        if (role.getRoleId() != null && sysRoleDepts != null) {
            roleDeptMapper.deleteRoleDeptByRoleId(role.getRoleId());
        }

        if (sysRoleMenus != null && sysRoleMenus.size() > 0) {
            Map<String, String> projectMap = new HashMap<>();
            if (role.getProjectCodes() != null && role.getProjectCodes().size() > 0) {
                role.getProjectCodes().forEach((projectCode) -> {
                    projectMap.put(projectCode, projectCode);
                });
            }
            for (SysRoleMenu sysRoleMenu : sysRoleMenus) {
                //只添加项目code之内的，但如何项目code为null默认是所有的
                if (role.getProjectCodes() != null && role.getProjectCodes().size() > 0) {
                    if (projectMap.containsKey(sysRoleMenu.getProjectCode())) {
                        sysRoleMenu.setRoleId(role.getRoleId());
                    }
                } else {
                    sysRoleMenu.setRoleId(role.getRoleId());
                }

            }
            successNum = roleMenuMapper.batchRoleMenu(sysRoleMenus);
        }

        if (sysRoleDepts != null && sysRoleDepts.size() > 0) {
            for (SysRoleDept sysRoleDept : sysRoleDepts) {
                sysRoleDept.setRoleId(role.getRoleId());
            }
            successNum = roleDeptMapper.batchRoleDept(sysRoleDepts);
        }

        return successNum;
    }

    /**
     * 修改角色状态
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    public int updateRoleStatus(SysRole role) {
        return this.updateRole(role);
    }

    /**
     * 修改数据权限信息
     *
     * @param role 角色信息
     * @return 结果
     */
    @Override
    @Transactional
    public int authDataScope(SysRole role) {

        return this.updateRole(role);
    }


    /**
     * 新增角色菜单信息
     *
     * @param role 角色对象
     */
    /*public int insertRoleMenu(SysRoleDto role) {

        //判断是否存在
        SysRoleDto sysRoleOrigin = roleMapper.selectRoleByDeptAndKey(role.getDeptId(),role.getRoleKey());

        //根据部门和roleKey获取所有的

        //根据deptId和roleKey删除所有的父级数据 判断当前的数据与父级别不一致的时候返回数据
        // 删除角色与菜单关联
        roleMenuMapper.deleteRoleMenuByRoleId(role.getRoleId());


        int rows = 1;
        // 新增用户与角色管理
        List<SysRoleMenu> list = new ArrayList<SysRoleMenu>();
        for (Long menuId : role.getMenuIds()) {
            SysRoleMenu rm = new SysRoleMenu();
            rm.setRoleId(role.getRoleId());
            rm.setMenuId(menuId);
            list.add(rm);
        }
        if (list.size() > 0) {
            rows = roleMenuMapper.batchRoleMenu(list);
        }
        return rows;
    }*/

    /**
     * 新增角色部门信息(数据权限)
     *
     * @param role 角色对象
     */
    /*public int insertRoleDept(SysRoleDto role) {
        int rows = 1;
        // 新增角色与部门（数据权限）管理
        List<SysRoleDept> list = new ArrayList<SysRoleDept>();
        for (Long deptId : role.getDeptIds()) {
            SysRoleDept rd = new SysRoleDept();
            rd.setRoleId(role.getRoleId());
            rd.setDeptId(deptId);
            list.add(rd);
        }
        if (list.size() > 0) {
            rows = roleDeptMapper.batchRoleDept(list);
        }
        return rows;
    }
*/

    /**
     * 通过角色ID删除角色
     *
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteRole(SysRoleUnique sysRoleKey) {

        //判断是否为顶层 如果为顶层并且存在继承不允许删除
        SysRole roleOld = this.selectRole(sysRoleKey.getDeptId(), sysRoleKey.getRoleKey());

        //获取原始的数据
        SysRole sysRoleOrigin = roleMapper.selectRoleByDeptAndKey(sysRoleKey.getDeptId(), sysRoleKey.getRoleKey());

        //判断是否为顶层
        if (roleOld.getIsTopFloor().equals("Y")) {
            if (roleOld.getIsAllowExtends().equals("Y")) {//当是允许继承的角色
                if (getExtendRoles(roleOld.getDeptId(), roleOld.getRoleKey()).size() > 0) {
                    throw new SystemException(SystemException.NOT_ALLOW_DELETE).setBusinessMessage("该角色存在继承，不允许修改");
                }
            }
        }

        //通过deptId和roleKey判断是否使用 如果使用了不允许删除 待优化
    /*     if (countUserRoleByRoleId(roleId) > 0) {
            throw new CustomException(String.format("%1$s已分配,不能删除", role.getRoleName()));
        }*/
        int successNum = 0;
        //当数据已经存在的时候
        if (sysRoleOrigin != null) {
            SysRole roleUpdate = new SysRole();
            roleUpdate.setRoleId(sysRoleOrigin.getRoleId());
            roleUpdate.setDelFlag("2");
            roleUpdate.setUpdateTime(DateUtils.getNowDate());
            roleUpdate.setUpdateBy(SecurityUtils.getUsername());
            successNum = roleMapper.updateRole(roleUpdate);
        } else {
            //当数据不存在的时候
            SysRole roleInsert = new SysRole();
            roleInsert.setDelFlag("2");
            roleInsert.setDeptId(sysRoleKey.getDeptId());
            roleInsert.setRoleKey(sysRoleKey.getRoleKey());
            roleInsert.setIsAllowExtends("Y");
            successNum = roleMapper.insertRole(roleInsert);

        }

        return successNum;
    }

    /**
     * 批量删除角色信息
     *
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteRoleByKeys(List<SysRoleUnique> sysRoleKeys) {
        if (sysRoleKeys == null || sysRoleKeys.size() == 0) {
            throw new SystemException(SystemException.NOT_ALLOW_DELETE).setBusinessMessage("没有可删除的数据");
        }
        int successNum = 0;
        for (SysRoleUnique sysRoleKey : sysRoleKeys) {
            successNum += this.deleteRole(sysRoleKey);
            /*SysRoleDto sysRole = new SysRoleDto();
            sysRole.setRoleId(roleId);
            checkRoleAllowed(sysRole);
            SysRoleDto role = selectRoleById(roleId);
            if (countUserRoleByRoleId(roleId) > 0) {
                throw new CustomException(String.format("%1$s已分配,不能删除", role.getRoleName()));
            }*/
        }
        return successNum;
    }

    @Override
    @Transactional
    public int batchUpdateRoleKey(Long deptId, String roleOldKey, String roleNewKey) {
        return roleMapper.batchUpdateRoleKey(deptId, roleOldKey, roleNewKey);
    }
}
